import express from 'express';
import { authenticateToken } from '../middleware/auth.js';
import pool from '../config/db.js';
import { alipaySdk, AlipayFormData } from '../config/alipay.js';
import { v4 as uuidv4 } from 'uuid';
import { sendMail } from '../config/mail.js';

const router = express.Router();

// 创建支付
router.post('/create', authenticateToken, async (req, res) => {
  try {
    const { order_id, payment_method, amount } = req.body;
    
    console.log(`Creating payment for order ${order_id} with method ${payment_method}`);
    
    if (!order_id || !payment_method || !amount) {
      return res.status(400).json({
        success: false,
        message: '缺少必要参数'
      });
    }
    
    // 查询订单信息
    const [orders] = await pool.query(
      'SELECT * FROM orders WHERE id = ? AND user_id = ?',
      [order_id, req.user.id]
    );
    
    if (orders.length === 0) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    
    const order = orders[0];
    
    // 生成支付流水号
    const paymentNo = `PAY${Date.now()}${Math.floor(Math.random() * 1000)}`;
    
    // 记录支付信息
    const [paymentResult] = await pool.query(
      'INSERT INTO payments (order_id, payment_no, payment_method, amount, status, user_id) VALUES (?, ?, ?, ?, ?, ?)',
      [order_id, paymentNo, payment_method, amount, 'pending', req.user.id]
    );
    
    const paymentId = paymentResult.insertId;
    
    // 根据支付方式处理
    if (payment_method === 'alipay') {
      try {
        // 支付宝支付 - 使用旧的方法，但确保返回URL而不是表单
        const formData = new AlipayFormData();
        formData.setMethod('get');  // 使用GET方法确保返回URL
        
        formData.addField('bizContent', {
          outTradeNo: paymentNo,
          productCode: 'FAST_INSTANT_TRADE_PAY',
          totalAmount: amount.toString(),
          subject: `StoryPlush订单-${order.order_no}`,
          body: `StoryPlush订单支付`
        });
        
        // 支付成功后跳转地址 - 改回购物车页面
        formData.addField('returnUrl', `${process.env.CLIENT_URL}/cart?payment_status=success&order_no=${order.order_no}`);
        
        // 异步通知地址
        const notifyUrl = process.env.USE_NGROK === 'true' 
          ? `${process.env.NGROK_SERVER_URL}/api/payments/notify`
          : `${process.env.SERVER_URL}/api/payments/notify`;
          
        console.log('Using notify URL:', notifyUrl);
        formData.addField('notifyUrl', notifyUrl);
        
        // 使用旧方法，但确保返回URL
        console.log('Using alipay.exec method with GET');
        const result = await alipaySdk.exec(
          'alipay.trade.page.pay',
          {},
          { formData: formData }
        );
        
        console.log('Alipay result type:', typeof result);
        console.log('Alipay result preview:', result.substring(0, 200) + '...');
        
        // 检查结果是否是URL还是HTML表单
        if (result.startsWith('http')) {
          // 如果是URL，直接返回
          return res.json({
            success: true,
            payment_url: result,
            payment_no: paymentNo,
            payment_id: paymentId
          });
        } else {
          // 如果是HTML表单，创建一个临时页面来提交表单
          return res.json({
            success: true,
            payment_html: result,  // 返回HTML表单
            payment_no: paymentNo,
            payment_id: paymentId,
            is_form: true  // 标记这是一个表单，而不是URL
          });
        }
      } catch (error) {
        console.error('Error creating Alipay payment:', error);
        return res.status(500).json({
          success: false,
          message: '创建支付宝支付失败'
        });
      }
    } else if (payment_method === 'wechat') {
      // 微信支付 - 暂未实现
      return res.json({
        success: false,
        message: '微信支付功能暂未开发'
      });
    } else {
      return res.status(400).json({
        success: false,
        message: '不支持的支付方式'
      });
    }
  } catch (error) {
    console.error('Error creating payment:', error);
    res.status(500).json({
      success: false,
      message: '创建支付失败'
    });
  }
});

// 支付宝异步通知
router.post('/notify', async (req, res) => {
  try {
    console.log('Received payment notification:', req.body);
    
    // 验证支付宝通知
    const signVerified = alipaySdk.checkNotifySign(req.body);
    
    if (!signVerified) {
      console.error('Payment notification verification failed');
      return res.status(400).send('fail');
    }
    
    const { out_trade_no, trade_status } = req.body;
    
    // 查询支付记录
    const [payments] = await pool.query(
      'SELECT * FROM payments WHERE payment_no = ?',
      [out_trade_no]
    );
    
    if (payments.length === 0) {
      console.error('Payment not found:', out_trade_no);
      return res.status(400).send('fail');
    }
    
    const payment = payments[0];
    
    // 如果支付已经处理过，直接返回成功
    if (payment.status !== 'pending') {
      return res.send('success');
    }
    
    // 处理支付状态
    if (trade_status === 'TRADE_SUCCESS' || trade_status === 'TRADE_FINISHED') {
      // 更新支付状态
      await pool.query(
        'UPDATE payments SET status = ?, updated_at = NOW() WHERE id = ?',
        ['paid', payment.id]
      );
      
      // 更新订单状态
      await pool.query(
        'UPDATE orders SET status = ?, payment_status = ?, updated_at = NOW() WHERE id = ?',
        ['paid', 'paid', payment.order_id]
      );
      
      // 发送支付成功邮件
      try {
        const [orderInfo] = await pool.query(
          'SELECT o.*, u.email FROM orders o JOIN users u ON o.user_id = u.id WHERE o.id = ?',
          [payment.order_id]
        );
        
        if (orderInfo.length > 0) {
          const order = orderInfo[0];
          await sendMail({
            to: order.email,
            subject: `StoryPlush - 订单支付成功 (${order.order_no})`,
            html: `
              <h1>您的订单已支付成功</h1>
              <p>订单号: ${order.order_no}</p>
              <p>支付金额: ¥${payment.amount}</p>
              <p>支付时间: ${new Date().toLocaleString()}</p>
              <p>感谢您的购买！</p>
            `
          });
        }
      } catch (mailError) {
        console.error('Error sending payment success email:', mailError);
      }
      
      console.log(`Payment successful for order ${payment.order_id}, updated status to paid`);
    }
    
    res.send('success');
  } catch (error) {
    console.error('Error processing payment notification:', error);
    res.status(500).send('fail');
  }
});

// 查询支付状态
router.get('/status/:orderId', authenticateToken, async (req, res) => {
  try {
    const { orderId } = req.params;
    
    // 查询支付记录
    const [payments] = await pool.query(
      'SELECT p.*, o.order_no FROM payments p JOIN orders o ON p.order_id = o.id WHERE p.order_id = ? AND p.user_id = ?',
      [orderId, req.user.id]
    );
    
    if (payments.length === 0) {
      return res.status(404).json({
        success: false,
        message: '支付记录不存在'
      });
    }
    
    const payment = payments[0];
    
    // 如果支付已完成，直接返回状态
    if (payment.status === 'paid') {
      return res.json({
        success: true,
        status: 'paid',
        order_number: payment.order_no
      });
    }
    
    // 查询支付宝订单状态
    if (payment.payment_method === 'alipay') {
      try {
        const formData = new AlipayFormData();
        formData.setMethod('get');
        formData.addField('bizContent', {
          outTradeNo: payment.payment_no
        });
        
        const result = await alipaySdk.exec(
          'alipay.trade.query',
          {},
          { formData: formData }
        );
        
        const response = JSON.parse(result);
        
        if (response.alipay_trade_query_response.code === '10000') {
          const tradeStatus = response.alipay_trade_query_response.trade_status;
          
          // 如果支付成功，更新状态
          if (tradeStatus === 'TRADE_SUCCESS' || tradeStatus === 'TRADE_FINISHED') {
            // 更新支付状态
            await pool.query(
              'UPDATE payments SET status = ?, updated_at = NOW() WHERE id = ?',
              ['paid', payment.id]
            );
            
            // 更新订单状态
            await pool.query(
              'UPDATE orders SET status = ?, payment_status = ?, updated_at = NOW() WHERE id = ?',
              ['paid', 'paid', payment.order_id]
            );
            
            return res.json({
              success: true,
              status: 'paid',
              order_number: payment.order_no
            });
          }
        }
      } catch (error) {
        console.error('Error querying alipay trade status:', error);
        // 查询失败时不要中断，继续返回当前状态
      }
      
      // 支付宝沙箱环境特殊处理 - 如果是从支付宝跳转回来的，直接更新为已支付
      if (req.query.from_alipay_return === 'true') {
        // 更新支付状态
        await pool.query(
          'UPDATE payments SET status = ?, updated_at = NOW() WHERE id = ?',
          ['paid', payment.id]
        );
        
        // 更新订单状态
        await pool.query(
          'UPDATE orders SET status = ?, payment_status = ?, updated_at = NOW() WHERE id = ?',
          ['paid', 'paid', payment.order_id]
        );
        
        return res.json({
          success: true,
          status: 'paid',
          order_number: payment.order_no,
          simulated: true
        });
      }
    }
    
    // 返回当前状态
    return res.json({
      success: true,
      status: payment.status,
      order_number: payment.order_no
    });
  } catch (error) {
    console.error('Error checking payment status:', error);
    res.status(500).json({
      success: false,
      message: '查询支付状态失败'
    });
  }
});

// 通过支付号查询支付状态
router.get('/status/by-payment-no/:paymentNo', authenticateToken, async (req, res) => {
  try {
    const { paymentNo } = req.params;
    
    // 查询支付记录
    const [payments] = await pool.query(
      'SELECT p.*, o.order_no FROM payments p JOIN orders o ON p.order_id = o.id WHERE p.payment_no = ? AND p.user_id = ?',
      [paymentNo, req.user.id]
    );
    
    if (payments.length === 0) {
      return res.status(404).json({
        success: false,
        message: '支付记录不存在'
      });
    }
    
    const payment = payments[0];
    
    // 如果支付已完成，直接返回状态
    if (payment.status !== 'pending') {
      return res.json({
        success: true,
        status: payment.status,
        order_number: payment.order_no
      });
    }
    
    // 查询支付宝订单状态
    if (payment.payment_method === 'alipay') {
      try {
        const result = await alipaySdk.exec(
          'alipay.trade.query',
          {
            bizContent: {
              out_trade_no: paymentNo
            }
          }
        );
        
        // 确保结果是 JSON 字符串
        const response = typeof result === 'string' ? JSON.parse(result) : result;
        
        if (response.alipay_trade_query_response) {
          const tradeStatus = response.alipay_trade_query_response.trade_status;
          
          // 如果支付成功，更新状态
          if (tradeStatus === 'TRADE_SUCCESS' || tradeStatus === 'TRADE_FINISHED') {
            // 更新支付状态
            await pool.query(
              'UPDATE payments SET status = ?, updated_at = NOW() WHERE id = ?',
              ['paid', payment.id]
            );
            
            // 更新订单状态
            await pool.query(
              'UPDATE orders SET status = ?, payment_status = ?, updated_at = NOW() WHERE id = ?',
              ['processing', 'paid', payment.order_id]
            );
            
            return res.json({
              success: true,
              status: 'paid',
              order_number: payment.order_no
            });
          }
        }
      } catch (error) {
        console.error('Error querying alipay trade status:', error);
        // 查询失败时不要中断，继续返回当前状态
      }
    }
    
    // 返回当前状态
    return res.json({
      success: true,
      status: payment.status,
      order_number: payment.order_no
    });
  } catch (error) {
    console.error('Error checking payment status by payment no:', error);
    res.status(500).json({
      success: false,
      message: '查询支付状态失败'
    });
  }
});

// 支付回调处理
router.post('/callback', async (req, res) => {
  try {
    const { order_id, payment_id, status } = req.body;
    
    if (!order_id || !payment_id || !status) {
      return res.status(400).json({
        success: false,
        message: '参数不完整'
      });
    }
    
    // 更新支付记录
    await pool.query(
      'UPDATE payments SET status = ?, updated_at = NOW() WHERE id = ?',
      [status, payment_id]
    );
    
    // 如果支付成功，更新订单状态
    if (status === 'paid') {
      await pool.query(
        'UPDATE orders SET status = ?, payment_time = NOW(), updated_at = NOW() WHERE id = ?',
        ['paid', order_id]
      );
      
      // 获取订单信息以便发送邮件通知
      const [orderRows] = await pool.query(
        'SELECT o.*, u.email, u.username FROM orders o JOIN users u ON o.user_id = u.id WHERE o.id = ?',
        [order_id]
      );
      
      if (orderRows.length > 0) {
        const order = orderRows[0];
        
        // 发送支付成功邮件
        try {
          await sendMail({
            to: order.email,
            subject: '订单支付成功',
            html: `
              <h1>您的订单已支付成功</h1>
              <p>订单号: ${order.order_number}</p>
              <p>支付金额: ¥${order.total_amount}</p>
              <p>支付时间: ${new Date().toLocaleString()}</p>
              <p>感谢您的购买！</p>
            `
          });
        } catch (emailError) {
          console.error('发送支付成功邮件失败:', emailError);
        }
      }
    }
    
    res.json({
      success: true,
      message: '支付回调处理成功'
    });
  } catch (error) {
    console.error('Error processing payment callback:', error);
    res.status(500).json({
      success: false,
      message: '处理支付回调失败'
    });
  }
});

export default router; 